package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.util.JwtUtil;
import com.example.demo.vo.LoginVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户服务类
 * 
 * @author zhang
 * @date 2024
 */
@Service
public class UserService {
    
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 用户登录
     * 校验用户状态，禁用用户无法登录
     */
    public LoginVO login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new BusinessException(401, "用户名或密码错误");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new BusinessException(401, "用户名或密码错误");
        }
        
        // 检查用户状态（0-禁用，1-启用）
        if (user.getStatus() == null || user.getStatus() == 0) {
            logger.warn("用户已被禁用: {}", username);
            throw new BusinessException(403, "用户已被禁用，无法登录");
        }
        
        logger.info("用户登录成功: {}", username);
        return buildLoginVO(user);
    }
    
    /**
     * 用户注册
     * 新注册用户默认为启用状态
     */
    public LoginVO register(User user) {
        // 检查用户名是否已存在
        User existUser = userMapper.findByUsername(user.getUsername());
        if (existUser != null) {
            throw new BusinessException(400, "用户名已存在");
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        // 新注册用户默认为启用状态（1-启用）
        user.setStatus(1);
        
        // 插入用户
        userMapper.insert(user);
        
        logger.info("用户注册成功: {}", user.getUsername());
        
        // 注册成功后返回登录信息
        return buildLoginVO(user);
    }
    
    /**
     * 构建LoginVO
     */
    private LoginVO buildLoginVO(User user) {
        // 生成Token
        String token = jwtUtil.generateToken(user.getId(), user.getUsername());
        
        // 构建响应
        LoginVO vo = new LoginVO();
        vo.setToken(token);
        vo.setTokenType("Bearer");
        
        LoginVO.UserInfoVO userInfo = new LoginVO.UserInfoVO();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setNickname(user.getNickname());
        userInfo.setEmail(user.getEmail());
        vo.setUserInfo(userInfo);
        
        return vo;
    }
}

